<?php
/**
 *  Class:   Mail
 *  Type:    Controller
 *  About:   Sending letters
 *  Authors: Vlad Andreev <php.vlad@gmail.com>
 **/

namespace Mail;

class Controller extends \Control\ControllerAncestor {
    
    private $repMail;
    private $texts = array();
    
    public function __construct() {
        
        parent::__construct();
        
        $this->repMail = $this->em->getrepository('Mail\Entities\Mail');
    }
    
    // Sending letter
    public static function send($event) {
        
        // Finding patterns of letters by behalf of the event
        $mails = $this->repMail->findBy(array(
            'event'  => $event,
            'active' => 1
        ));
        
        foreach ($mails as $mail) {
            $subject = htmlspecialchars_decode($mail->subject);
            $message = htmlspecialchars_decode($mail->text);
            $tags    = explode(',', $mail->tags);
            
            // Replacement tag in a letter to the values ​​of variables
            foreach ($tags as $tag) {
                $tag = explode('.', $tag);
                
                if(is_array($GLOBALS[$tag[0]]))
                    $value = $GLOBALS[$tag[0]][$tag[1]];
                elseif(is_object($GLOBALS[$tag[0]]))
                    $value = $GLOBALS[$tag[0]]->$tag[1];
                else
                    $value = $GLOBALS[$tag[0]];
               
                $subject = str_replace('{'. $tag[0] .'.'. $tag[1] .'}', $value, $subject);
                $message = str_replace('{'. $tag[0] .'.'. $tag[1] .'}', $value, $message);
            }
            
            $mail_to = $user->email;
            $mail_from = $conf->site_mail;
            
            // Sending letter
            if ($subject != '' && $message != '') {
                $headers  = 'MIME-Version: 1.0' . "\r\n";
                $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
                $headers .= 'To: '. $user->name .' <'. $mail_to .'>' . "\r\n";
                $headers .= 'From: '. $conf->site_name .' <'. $mail_from .'>' . "\r\n";
                
                mail($mail_to, $subject, $message, $headers);
            }
        }
    }
    
    // The list of letters
    public function listAction() {
        
        $form = new \Control\Forms;
        $form->setTitle('Письма');
        $form->setTemplate('list');
        
        $form->addHead(array(
            array('width' => 1),
            array('width' => 400, 'align' => 'left', 'text' => 'Название'),
            array('width' => 1),
            array('width' => 1)
        ));
        
        $rows = array();
        
        $mails = $this->repMail->findBy(array());
        foreach ($mails as $mail) {
            $edit = array(
                'type' => 'link_img_edit',
                'href' => '#Mail/edit/'. $mail->id
            );
            
            $title = array(
                'type' => 'link',
                'href' => '#Mail/edit/'. $mail->id,
                'text' => $mail->title
            );
            
            $active = ($mail->active == 1)
                ? array(
                    'type' => 'link_img_active',
                    'action' => "acDisable('mail','". $mail->id ."');")
                : array(
                    'type' => 'link_img_disable',
                    'action' => "acActivate('mail','". $mail->id ."');")
            ;
            
            $delete = array(
                'type'   => 'link_img_delete',
                'action' => "javascript: if (MsgOkCancel('Вы действительно хотите удалить это письмо?')) { acDelete('mail','". $mail->id ."'); }"
            );
            
            $rows[] = array($edit, $title, $active, $delete);
        }
        
        $form->addRows($rows);
        
        return $form->render();
    }
    
    // The list of options
    public function optionsAction() {
        
        $json = array();
        
        $childs = array();
        $mails = $this->repMail->findBy(array());
        foreach ($mails as $mail)
            $childs[] = array('title' => $mail->title, 'href' => '#Mail/edit/'. $mail->id);
        
        $json[] = array('title' => 'Добавить письмо', 'href' => '#Mail/add');
        $json[] = array('title' => 'Список писем', 'href' => '#Mail/list', 'childs'=>$childs);
        
        return json_encode($json);
    }
    
    // Adding form letters
    public function addAction() {
        
        $data = new \Data\Data;
        $data->setName('Mail');
        $output = $data->addForm(array('title' => 'Добавить письмо'));
        
        return $output;
    }
    
    // Editing form letters
    public function editAction($id) {
        
        $mail = new \Mail\Mail;
        $item = $mail->find(intval($id));
        
        if (!$item) {
            $form = new \Control\Forms;
            $form->setTitle('Письмо не найдено');
            $form->setTemplate('form');
            $form->addHTML('<br/>К сожалению, по Вашему запросу ничего не найдено.<br/><br/><a class="js-link" href="#Mail/list">← Вернуться к списку писем</a>');
            
            return $form->render();
        }
        
        $data = new \Data\Data;
        $data->setName('Mail');
        $data->setData($item);
        
        $output = $data->editForm(array(
            'title'          => 'Редактировать письмо',
            'deleteQuestion' => 'Вы действительно хотите удалить это письмо?'
        ));
        
        return $output;
    }
    
    // Save action
    public function saveAction($data_name, $id = null) {
        
        $mail = new \Mail\Mail;
        $res = $mail->save($_POST, $id);
        
        return $this->statusOk();
    }
    
    // Delete action
    public function deleteAction($data_name, $id) {
        
        $id = intval($id);
        
        $mail = new \Mail\Mail;
        $mail->delete($id);
        
        return $this->statusOk();
    }
    
    // Activate action
    public function activateAction($data_name, $id) {
        
        $id = intval($id);
        
        $mail = new \Mail\Mail;
        $mail->save(array('active' => 1), $id);
        
        return $this->statusOk();
    }
    
    // Disable action
    public function disableAction($data_name, $id) {
        
        $id = intval($id);
        
        $mail = new \Mail\Mail;
        $mail->save(array('active' => 0), $id);
        
        return $this->statusOk();
    }
}